/**
 * 
 */
package ltu.m7011e.client;

import ltu.m7011e.shared.SharedConstants;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.Window;
import com.google.gwt.xml.client.Document;

/**
 * @author robinelmouahidine
 *
 */
public class LinkServiceRequester {

	/**
	 * An instance of the Shared Constants.
	 */
	private final SharedConstants constants = GWT.create(SharedConstants.class);
	
	private HandlerManager eventBus;

	public void postLink(Document xmlLinkToSend){
		// TODO : Use properties to save url ! 
		String url = constants.cAPIPostLinkURL();
		RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));

		try {
			// Send the POST Request
			builder.setHeader("Content-Type", "application/xml");
			Request postLinkRequest = builder.sendRequest(xmlLinkToSend.toString(), new RequestCallback() {	
				public void onResponseReceived(Request request, Response response) {
					if (200 == response.getStatusCode()) {
						GWT.log("postLinkRequest - Success !! ");
						Window.alert("Your link have been posted !");
					} else {
						GWT.log("postLinkRequest - ERROR != 200 : ");
					}
				}

				public void onError(Request request, Throwable exception) {
					GWT.log("postLinkRequest - FAIL : "+exception.getMessage());
					Window.alert("A problem occured - Your Link haven't been post ... ");
				}
			});
		} catch (RequestException e) {
			GWT.log("[ERROR] RequestException :"+e.getMessage());
			Window.alert("An exception have been thrown - Your Link haven't been post ...");
		}
	}

	
	public LinkServiceRequester( HandlerManager eventBus){
		this.eventBus = eventBus;
	}

}
